<?php

namespace addons\yungift\controller;

use addons\yungift\library\Super;
use addons\yungift\model\FundUser;
use addons\yungift\model\GiftMain;

/**
 * 首页接口
 */
class Page extends BaseApi
{
    // 获取首页数据
    public function getHomeData()
    {
        // 活动数据
        $activityInfo = Super::arrayGetSet($this->activityData, ['name', 'start_time', 'end_time', 'state']);

        // 用户数据
        $userInfo = Super::arrayGetSet($this->memberData, [
            'name',
            'group_name' => function ($item) {
                return $item->groupText;
            },
            'avatar_url'
        ]);

        // 礼品账户
        if (! $fundUser = FundUser::get(['activity_id' => $this->activityId, 'member_id' => $this->memberId])) {
            $this->error(__('礼币账户未激活，请联系管理员处理'));
        }
        $fundInfo = Super::arrayGetSet($fundUser, [
            'amount_left',
            'status',
            'status_text'
        ]);

        // 热门兑换
        $hotList = GiftMain::where(['status' => GiftMain::STATUS_NORMAL])
            ->where('start_time', ['>', 0], ['<=', time()], 'and')
            ->where('end_time', ['>', 0], ['>', time()], 'and')
            ->where('find_in_set(:aid, `activity_ids`)', ['aid' => $this->activityId])
            ->where('(group_ids is null or group_ids=\'\' or find_in_set(:gid, `group_ids`))',
                ['gid' => $this->memberData->group_id])
            ->order('count_gain DESC, weight DESC, id DESC')->limit(10)->select();
        $hotList = Super::arrayGetSet($hotList, [
            'id',
            'type',
            'name',
            'cover_url',
            'worth',
            'amount',
            'multi_spec',
            'count_left',
            'count_gain',
            'created_at',
        ], true);

        // 全部礼品
        $giftList = GiftMain::where(['status' => GiftMain::STATUS_NORMAL])
            ->where('start_time', ['>', 0], ['<=', time()], 'and')
            ->where('end_time', ['>', 0], ['>', time()], 'and')
            ->where('find_in_set(:aid, `activity_ids`)', ['aid' => $this->activityId])
            ->where('(group_ids is null or group_ids=\'\' or find_in_set(:gid, `group_ids`))',
                ['gid' => $this->memberData->group_id])
            ->order('weight DESC, id DESC')->limit(10)->select();
        $giftList = Super::arrayGetSet($giftList, [
            'id',
            'type',
            'name',
            'cover_url',
            'worth',
            'amount',
            'multi_spec',
            'count_left',
            'count_gain',
            'created_at',
        ], true);

        $this->success('操作成功', compact('activityInfo', 'userInfo', 'fundInfo', 'hotList', 'giftList'));
    }
}
